package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

/**
 * 使用反射机制实例化对象
 * @author pc
 *
 */
public class ReflectDemo2 {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		//硬编码方式实例化
		Person p = new Person();
		System.out.println(p);
		ArrayList a = new ArrayList();
		System.out.println(a);
		
		/*
		 * 使用反射机制:
		 * 1:加载要实例化对象的类的类对象
		 * 2:通过类对象的newInstance方法实例化 
		 */
		//实例化Person
		Class<?> cls = Class.forName("reflect.Person");
		//需要注意newInstance方法要求Class表示的类必须有无参构造器
		Object obj = cls.newInstance();		
		System.out.println(obj);
		
		
		
		
		//硬编码方式调用有参数构造器
		Student stu = new Student("张三",22);
		System.out.println(stu);
		/*
		 * 利用有参构造器实例化对象
		 * 1:加载要实例化的类的类对象
		 * 2:通过类对象获取指定的构造方法
		 * 3:利用该构造方法实例化
		 */
		//1
		Class cls1 = Class.forName("reflect.Student");
		//2  Student(String name, int age)
		Constructor c = cls1.getConstructor(String.class,int.class);
		Object o1 = c.newInstance("李四",18);
		System.out.println(o1);
		
	}
}














